package com.haiheng.module_main.mode

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.api.API.BOOK_CAR_PATH.Companion.PARAGE_BARCODES
import com.haiheng.common.api.API.BOOK_CAR_PATH.Companion.PARAGE_MACHINEUUID
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.HttpResponse
import com.haiheng.library_base.http.get
import com.haiheng.library_base.http.patch
import com.haiheng.library_base.http.post
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.module_main.bean.res.bookcar.BookCarBookInfoRes
import com.haiheng.module_main.bean.res.bookcar.BookCarBookResult
import kotlinx.coroutines.launch
import java.text.FieldPosition

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/8/20 0020
 * @Version: 1.0
 */
class BookCarScanViewModel : BaseViewModel() {
    // 使用MutableLiveData<List<Pair<String, String>>>来存储书车信息的键值对列表
    var _bookInfoList = MutableLiveData<List<BookCarBookResult>>(emptyList())
    var _faiMsg = MutableLiveData<String>()

    // 提供一个不可变的LiveData给观察者
    val bookInfoList: LiveData<List<BookCarBookResult>> = _bookInfoList
    val faiMsg: LiveData<String> = _faiMsg

    fun queryBookDetail(carNum: String?) {
        viewModelScope.launch {
            try {

                val request = HttpRequest(API.BOOK_CAR_PATH.GET_BOOK_INFO)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .putPath("Barcodes",carNum.toString())
                var response = get<BookCarBookInfoRes>(request) {}
                if (response.errorCode.equals("0")){
                    val newBooks = mutableListOf<BookCarBookResult>()
                    val existingBarcodes = _bookInfoList.value?.map { it.barcode }?.toSet() ?: emptySet()
                    var bookInfo = response.result
                    if (!existingBarcodes.contains(bookInfo.barcode)) {
                        newBooks.add(bookInfo) // 假设你有一个转换方法
                    }

//                    // 合并新旧列表（如果你需要保留旧列表中的书籍）
                    val updatedList = (_bookInfoList.value ?: emptyList()) + newBooks
                    _bookInfoList.postValue(updatedList)
                }else{
                    _faiMsg.postValue(response.message)
                    LogWriter.d("查询书籍信息异常：${response}")
                }
//                var list = mutableListOf<BookInfoBean>()
//                // 构建书车信息的键值对列表
//                for (i in 1..20){
//                  var b =   BookInfoBean(bookTitle = "书名${i}", barCode = "${i}", bookRecordNo ="索书${i}" );
//                    list.add(b)
//                }


                // 更新LiveData
//                _bookInfoList.postValue(list)
            } catch (ex: Exception) {
                _faiMsg.postValue("${ex}")
                LogWriter.d("查询书车异常：${ex.message}")
            }
        }
    }

    fun finScan(bookInfoList: MutableList<BookCarBookResult>) {
        viewModelScope.launch {
            try {
                val par = mutableMapOf<String, List<String>>()

                var barcodes = mutableListOf<String>()
                for (book in bookInfoList){
                    barcodes.add(book.barcode)
                }
                par.put("barcodes",barcodes)
                val request = HttpRequest(API.BOOK_CAR_PATH.ADD_SCAN_BOOK)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
//                    .putQueryParams(PARAGE_BARCODES,barcodes)
                    .setJsonObjec(par)
                    .putPath(PARAGE_MACHINEUUID,AppConstant.getCarUUid())

                var response = postJson<HttpResponse>(request) {}
                LogUtils.d("完成扫描：${response.toJson()}")
                if (response.errorCode.equals("0")){
                    _faiMsg.postValue("扫描完成")
                }else{
                    _faiMsg.postValue("${response.message}")
                    LogWriter.d("添加扫描异常：${response}")

                }
            }catch (ex:Exception){
                _faiMsg.postValue("${ex}")
                LogWriter.d("查询书车异常：${ex.message}")
            }
        }
    }

    fun deleteBook(bookResult: BookCarBookResult){
        val currentBookList = _bookInfoList.value ?: return // 如果列表为空，则直接返回

        // 创建一个新的列表来存储不包含要删除书籍的剩余书籍
        val filteredBookList = currentBookList.filterNot { book ->
            // 假设每个 BookCarBookResult 都有一个 id 属性
            book.barcode == bookResult.barcode // 只保留那些 ID 不等于要删除书籍 ID 的书籍
        }

        // 将更新后的列表设置回 _bookInfoList
        _bookInfoList.postValue(filteredBookList)
    }

    fun addBookList(bookCarBookResults: List<BookCarBookResult>) {
        _bookInfoList.postValue(bookCarBookResults)
    }
}